﻿using IMServer.Models;
using MongoDB.Driver;
using IMServer.Database;

namespace IMServer.Services
{
    public class UserDbService
    {
        private static readonly UserDbService _instance = new UserDbService();
        private static IMongoCollection<User>? _usersCollection;

        // 私有构造函数
        private UserDbService()
        {
            try
            {
                Console.WriteLine("Starting UserDbService initialization...");
                var dbContext = MongoDBContext.Instance;
                _usersCollection = dbContext.Users;
                
                if (_usersCollection == null)
                    throw new InvalidOperationException("Failed to initialize users collection");

                // 创建索引
                var indexOptions = new CreateIndexOptions { Unique = true };
                var indexKeys = Builders<User>.IndexKeys.Ascending(static x => x.UserId);
                _ = _usersCollection.Indexes.CreateOne(new CreateIndexModel<User>(indexKeys, indexOptions));
                
                Console.WriteLine("UserDbService initialized successfully");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error initializing UserDbService: {ex.Message}");
                throw;
            }
        }

        public static UserDbService Instance => _instance;

        // 插入新用户
        public async Task<bool> InsertUserAsync(User user)
        {
            if (_usersCollection == null)
                throw new InvalidOperationException("Database not initialized");
            
            try 
            {
                await _usersCollection.InsertOneAsync(user);
                return true;
            }
            catch (MongoWriteException ex) when (ex.WriteError.Category == ServerErrorCategory.DuplicateKey)
            {
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }

        // 使用UserId字段查询，而不是_id
        public async Task<User> GetUserByUserIdAsync(string userId)
        {
  
            return await _usersCollection.Find(x => x.UserId == userId).FirstOrDefaultAsync();
        }

        // 使用用户名查询
        public async Task<User> GetUserByUsernameAsync(string username)
        {
            return await _usersCollection.Find(x => x.UserName == username).FirstOrDefaultAsync();
        }

        // 添加好友
        public async Task<bool> AddFriendAsync(string userId, string friendId)
        {
            if (_usersCollection == null)
                throw new InvalidOperationException("Database not initialized");

            var update = Builders<User>.Update.AddToSet(x => x.Friends, friendId);
            var result = await _usersCollection.UpdateOneAsync(
                x => x.UserId == userId,
                update);
            
            return result.ModifiedCount > 0;
        }

        // 加入群组
        public async Task<bool> JoinGroupAsync(string userId, string groupId)
        {
            if (_usersCollection == null)
                throw new InvalidOperationException("Database not initialized");

            var update = Builders<User>.Update.AddToSet(x => x.Groups, groupId);
            var result = await _usersCollection.UpdateOneAsync(
                x => x.UserId == userId,
                update);
            
            return result.ModifiedCount > 0;
        }
        
        public async Task<IEnumerable<User>> GetUserFriendsAsync(string userId)
        {
            if (_usersCollection == null)
                throw new InvalidOperationException("Database not initialized");

            // 获取用户信息
            var user = await GetUserByUserIdAsync(userId);
            if (user?.Friends == null) return new List<User>();
            
            // 查询所有好友的用户信息
            var filter = Builders<User>.Filter.In(x => x.UserId, user.Friends);
            return await _usersCollection.Find(filter).ToListAsync();
        }

        public async Task<IEnumerable<Group>> GetUserGroupsAsync(string userId)
        {
            if (_usersCollection == null)
                throw new InvalidOperationException("Database not initialized");

            // 获取用户信息
            var user = await GetUserByUserIdAsync(userId);
            if (user?.Groups == null) return new List<Group>();
            
            // 需要从 GroupDbService 获取群组信息
            var groupService = GroupDbService.Instance;
            var groups = await groupService.GetGroupsByIdsAsync(user.Groups);
            return groups;
        }

        // 加入群组，在Groups中添加groupId
        public async Task AddGroupToUserAsync(string userId, string groupId)
        {
            var update = Builders<User>.Update.AddToSet(x => x.Groups, groupId);
            await _usersCollection.UpdateOneAsync(x => x.UserId == userId, update);
        }

        public async Task<IEnumerable<User>> GetUsersByIdsAsync(IEnumerable<string> userIds)
        {
            if (_usersCollection == null)
                throw new InvalidOperationException("Database not initialized");
            
            var filter = Builders<User>.Filter.In(x => x.UserId, userIds);
            return await _usersCollection.Find(filter).ToListAsync();
        }
    }
}